package ar.com.e2solver.solver.operator;

import ar.com.e2solver.model.Coordinate;
import ar.com.e2solver.model.NeighbourDirectionEnum;
import ar.com.e2solver.model.Piece;
import ar.com.e2solver.model.Puzzle;

public final class OperatorUtil {

	private OperatorUtil(){}
	
	public static void rotateForBorder(Coordinate c, Puzzle p) {
		int i = c.getX();
		int j = c.getY();
		Piece piece = p.getPieceAt(c);
		
		if(i == 0 ){
			while(!piece.getTop().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}
		} else if(j == 0){
			while(!piece.getLeft().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}
			
		} else if(i > j){
			while(!piece.getBottom().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}
			
		} else {
			while(!piece.getRight().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}	
		}
	}

	public static void rotateForCorner(Coordinate c, Puzzle p) {
		int i = c.getX();
		int j = c.getY();
		Piece piece = p.getPieceAt(c);
		
		if(i == 0 && j == 0){
			while(!piece.getLeft().equals(Piece.BORDER_COLOR) || !piece.getTop().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}
		} else if(i == 0 && j != 0){
			while(!piece.getRight().equals(Piece.BORDER_COLOR) || !piece.getTop().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}
		} else if(i != 0 && j == 0){
			while(!piece.getLeft().equals(Piece.BORDER_COLOR) || !piece.getBottom().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}			
		} else {
			while(!piece.getRight().equals(Piece.BORDER_COLOR) || !piece.getBottom().equals(Piece.BORDER_COLOR)){
				piece.rotateToRight(1);
			}			
		}
	}
	
	public static void rotate(Coordinate c, Puzzle puzzle) {
		Piece piece = puzzle.getPieceAt(c);
		int maxValue = 0;
		int rotationTimes = 0;
		
		int iValue = 0;
		for (int i = 0; i < 4; i++) {
			iValue = sumMatchedAdyacents(puzzle, c);
			if(maxValue < iValue ){
				maxValue = iValue;
				rotationTimes = i;
			}
			piece.rotateToRight(1);
		}
		
		piece.rotateToRight(rotationTimes);
	}
	
	public static int sumMatchedAdyacents(Puzzle puzzle, Coordinate c) {
		int sum = 0;
		Piece piece = puzzle.getPieceAt(c);
		
		if(puzzle.getNeighbour(c, NeighbourDirectionEnum.TOP).getBottom().equals(piece.getTop())){
			sum++;
		}
		
		if(puzzle.getNeighbour(c, NeighbourDirectionEnum.RIGHT).getLeft().equals(piece.getRight())){
			sum++;
		}
		
		if(puzzle.getNeighbour(c, NeighbourDirectionEnum.BOTTOM).getTop().equals(piece.getBottom())){
			sum++;
		}
		
		if(puzzle.getNeighbour(c, NeighbourDirectionEnum.LEFT).getRight().equals(piece.getLeft())){
			sum++;
		}
		
		return sum;
	}
}